package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.igas.bomp.facade.BompMchntPublicDealService;
import cc.rengu.igas.bomp.facade.request.MchntEntryDispatchRequest;
import cc.rengu.igas.bomp.facade.response.MchntEntryDispatchResponse;
import cc.rengu.igas.bomp.facade.result.Result;
import cc.rengu.redp.bizimpl.enums.BompTxnNumEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.MchntApplyInfo;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 刘玉亮.LL
 */
@Slf4j
@Api(tags = "商户管理:商户申请派单")
@RestController
@RequestMapping(value = "/admin/merParam/mchntApplyInfo")
public class MchntApplyInfoController extends BaseController {
    @Autowired
    private IMchntApplyInfoService mchntApplyInfoService;

    @Autowired
    private IUpmpOrganizationService organizationService;

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;


    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompMchntPublicDealService mchntManageService;


    //@RequiresPermissions("mchntApply:view")
    @GetMapping(value = "/list")
    public Map<String, Object> findByPage(QueryRequest request, MchntApplyInfo entity) {
        return getDataTable(this.mchntApplyInfoService.findByPage(request, entity));
    }


    @PostMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "applyId", value = "申请单号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "managerId", value = "拓展经理姓名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "managerPhone", value = "拓展经理手机号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "orgCode", value = "签约机构代码", required = true, dataType = "String")
    })
    public OperationResult editSave(@ModelAttribute("mchntApplyInfo") MchntApplyInfo entity, Model model, HttpServletRequest request) throws RedpException {
        String orgCode = request.getParameter("orgCode");
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        MchntEntryDispatchRequest req = new MchntEntryDispatchRequest();
        String traceNo = bMchntBaseInfoService.genMerOrder(entity.getInstId());
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.mchntEntryDispatch.getType(), entity.getInstId(),null));

        req.setUserId(user.getId());
        req.setApplyId(entity.getApplyId());//商户号与商户OPENID关系
        req.setSignInstId(orgCode);
        req.setManagerId(entity.getManagerId());
        req.setManagerPhone(entity.getManagerPhone());

        log.info("法人行[" + user.getInstId() + "],用户标识[" + req.getUserId() + "]" + BompTxnNumEnum.mchntEntryDispatch.getDesc() + "交易请求报文：" + JSON.toJSONString(req));
        Result<MchntEntryDispatchResponse> res = new Result<>();
        try {
            res = mchntManageService.mchntEntryDispatch(req);
        } catch (Exception e) {
            log.error("商户入驻申请处理时系统异常:[{}]", e);
            throw new RedpException("商户入驻申请处理时系统异常,请联系管理员");
        }
        log.info("法人行[" + user.getInstId() + "],用户标识[" + req.getUserId() + "]" + BompTxnNumEnum.mchntEntryDispatch.getDesc() + "交易返回报文：" + JSON.toJSONString(res));
        if (null == res || null == res.getResult()) {
            log.error("商户入驻申请处理时接口调用失败:result=[{}]", JSON.toJSONString(res));
            throw new RedpException("商户入驻申请处理时接口调用失败");
        }
        if (!BusinessContainer.BSPS_SUCCESS.equals(res.getResult().getRespCode())) {
            log.error("商户入驻申请处理时失败:code=[{}],msg=[{}]", res.getResult().getRespCode(), res.getResult().getRespDesc());
            throw new RedpException("商户入驻申请处理时失败:" + res.getResult().getRespDesc());
        }

        this.mchntApplyInfoService.updateById(entity);

        return OperationResult.buildSuccessResult("商户申请派单操作成功！");
    }
}
